import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import * as compDiviService from '../../../services/AccountDivi';
const daoName = "VCompBldkGlgrh";
const ButtonGroup = Button.Group;
const columns = [
  { title: '证件号码', width: 150, sorter: true, dataIndex: 'IDNO', key: 'IDNO', dispaly: true, filter: true },
  { title: '客户名称', width: 70, sorter: true, dataIndex: 'INCN', key: 'INCN', dispaly: true, filter: true },
  { title: '电话', width: 80, sorter: true, dataIndex: 'TLNO', key: 'TLNO', dispaly: true, filter: true },
  { title: '地址', width: 200, sorter: true, dataIndex: 'ADDR', key: 'ADDR', dispaly: true, filter: true },
  { title: '邮编', width: 120, sorter: true, dataIndex: 'POCD', key: 'POCD', dispaly: false, filter: true },
  { title: '电子邮箱', width: 165, sorter: true, dataIndex: 'EMAL', key: 'EMAL', dispaly: false, filter: true },
  { title: '客户ID', width: 120, sorter: true, dataIndex: 'KHID', key: 'KHID', dispaly: false, filter: true },
];
const controls = [
  { name: 'IDNO', required: true, type: 'text', label: '证件号码', grid: 12 / 24 },
  { name: 'INCN', required: true, type: 'text', label: '客户名称', grid: 12 / 24 },
  { name: 'TLNO', required: true, type: 'text', label: '电话', grid: 12 / 24 },
  { name: 'ADDR', required: true, type: 'text', label: '地址', grid: 12 / 24 },
  { name: 'POCD', required: true, type: 'text', label: '邮编', grid: 12 / 24 },
  { name: 'EMAL', required: true, type: 'text', label: '电子邮箱', grid: 12 / 24 },
  { name: 'KHID', required: true, type: 'text', label: '客户ID', grid: 12 / 24 },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class CompClieInfoBlGrForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      zhmData: {},
      khid: null
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "ID", permID: this.props.permID }
    });
    this.loadOptionData();
  }
  componentWillReceiveProps(nextProps) {
    const l1 = nextProps.masterSelectedRowKeys.length
    const l2 = this.props.masterSelectedRowKeys.length
    let k1 = -1
    let k2 = -1
    if (l1 > 0) {
      k1 = nextProps.masterSelectedRowKeys[l1 - 1]
    }
    if (l2 > 0) {
      k2 = this.props.masterSelectedRowKeys[l2 - 1]
    }
    if (k1 !== k2) {
      let seeks = [];
      let whereItems = [];
      let WhereCauses = [];
      whereItems.push({
        FieldName: "KHID",
        Operator: "=",
        FieldValues: '' + k1
      })
      WhereCauses.push({
        WhereItems: whereItems,
        RelationSign: "AND"
      })
      this.state.khid = k1
      seeks = WhereCauses;
      this.props.dispatch({
        type: `${daoName}/fetch`,
        payload: { daoName, page: 1, pageSize: 5, seeks }
      });
    }
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  showModelHandler(isAdd) {
    let key = null
    if (!isAdd) {
      const len = this.props.selectedRowKeys.length;
      if (len === 0) {
        message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
        return;
      }
      key = this.props.selectedRowKeys[len - 1]
    }
    this.props.dispatch({
      type: `${daoName}/openEdit`,
      payload: { key }
    });
  }
  saveData() {
    let khid = this.state.khid
    if (khid === null) {
      message.error("请在上方数据中选择一个客户数据")
      return
    }
    let ID = this.state.zhmData.NO
    if (ID === undefined) {
      message.error("请输入证件号码或客户名称")
      return
    }
    let id = Number(ID)
    let date = new Date()
    let month = date.getMonth() + 1
    let RDSJ = date.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + "01";
    compDiviService.AddCompbldkGrh({ khid, id, RDSJ }).then(function (data) {
      if (data === "OK") {
        message.success("添加个人关联户成功！")
      }
      let seeks = [];
      let whereItems = [];
      let WhereCauses = [];
      whereItems.push({
        FieldName: "KHID",
        Operator: "=",
        FieldValues: '' + this.state.khid
      })
      WhereCauses.push({
        WhereItems: whereItems,
        RelationSign: "AND"
      })
      seeks = WhereCauses;
      this.state.zhmData = {}
      this.props.dispatch({
        type: `${daoName}/fetch`,
        payload: { daoName, page: 1, pageSize: 5, seeks }
      });
      const form = this.refs.CompClieInfoBlForm.getForm();
      form.resetFields();
    }.bind(this))
  }
  DeleteData() {
    const len = this.props.selectedRowKeys.length;
    if (len === 0) {
      message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
      return;
    }
    let id = this.props.selectedRowKeys[len - 1]
    compDiviService.DelCompbldkGrh({ id }).then(function (data) {
      if (data === "OK") {
        message.success("删除个人关联户成功！")
      }
      let seeks = [];
      let whereItems = [];
      let WhereCauses = [];
      whereItems.push({
        FieldName: "KHID",
        Operator: "=",
        FieldValues: '' + this.state.khid
      })
      WhereCauses.push({
        WhereItems: whereItems,
        RelationSign: "AND"
      })
      seeks = WhereCauses;
      this.props.dispatch({
        type: `${daoName}/fetch`,
        payload: { daoName, page: 1, pageSize: 5, seeks }
      });
    }.bind(this))
  }
  seachHandler(data) {
    this.state.zhmData = data;
  }
  render() {
    let { showEdit, record, offsetHeight, masterSelectedRowKeys, permID, popedomTypes } = this.props
    let table2Height = (offsetHeight - 128) * 0.5 - 70
    const pTypes = popedomTypes[permID]
    let datas = []
    const controlsFilter = [];
    if (pTypes.indexOf("2") !== -1) {
      datas.push({ value: '1', label: '添加', onClick: this.saveData.bind(this) }, { value: '2', label: '删除', onClick: this.DeleteData.bind(this) })
      controlsFilter.push(
        { name: 'DGKH', required: false, type: 'search', label: '个人客户', grid: 13 / 24, layout: { labelSpan: 8, wrapperSpan: 15 }, fetch: { daoName: 'TIndiClie', searchColumns: ['Name', 'IDNO'], optionTpl: 'Name', valueTpl: "NO", onSelect: this.seachHandler.bind(this) }, placeholder: '请输入证件号码或客户名称' },
      )
      controlsFilter.push({ name: 'CX', required: false, type: 'button-group', data: datas, grid: 10 / 24 })
    }
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -0, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}>
            <EditFrom ref="CompClieInfoBlForm" daoName={daoName} controls={controlsFilter} record={record} clearItemMargin={true} />
          </div>
          <DataTable ref="userTable" daoName={daoName} columns={columns} controls={controls} height={table2Height} canExport={false} permID={permID} footerPageDisabled={true} />
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
  const masterSelectedRowKeys = state['VCompClie'].selectedRowKeys;
  const { offsetHeight, popedomTypes } = state.menus
  return {
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record,
    masterSelectedRowKeys
  }
}
CompClieInfoBlGrForm = connect(mapStateToProps)(CompClieInfoBlGrForm)
export default CompClieInfoBlGrForm;

let render = (props) => React.createElement(CompClieInfoBlGrForm, props);
let f = new Factory()
f.set("CompClieInfoBlGrForm", render) 
